const { Op, where } = require('sequelize');
const { Courses, Users, Category } = require('../../models');
const { NotFounError, success, fail } = require('../../utils/response');
// 查询课程列表处理函数
exports.getcourses = async (req, res) => {
    // try catch 处理数据
    try {
        const query = req.query
        // 当前是第几页,如果不传默认第一页
        const pageNo = Math.abs(Number(query.pageNo)) || 1
        // 每页显示多少条数据,如果不传,那就是显示10条
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        const offset = (pageNo - 1) * pageSize

        // id倒序
        const condition = {
            // 排除关联表的字段
            attributes: {
                exclude: ['categoryId', 'userId']
            },
            include: [
                {
                    model: Category,
                    as: 'category',
                    // 只返回id和name字段
                    attributes: ['id', 'name']
                },
                {
                    model: Users,
                    as: 'user',
                    // 只返回id和username字段avatar字段
                    attributes: ['id', 'username', 'avatar']
                }
            ],
            // order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        }
        const { count, rows } = await Courses.findAndCountAll(condition);

        success(res, '查询课程成功!', {
            courses: rows,
            paginations: {
                total: count,
                pageNo,
                pageSize
            }
        })
    } catch (error) {
        fail(res, error)
    }

};
//通过用户id查询课程列表处理函数
exports.getcoursesbyuser = async (req, res) => {
    try {
        const { userId } = req.user;
        const query = req.query
        const courses = await Courses.findOne({ where: { userId: userId } });
        if (!courses) {
            throw new NotFounError(`ID:${userId}的用户没有找到课程`);
        }
        // 当前是第几页,如果不传默认第一页
        const pageNo = Math.abs(Number(query.pageNo)) || 1
        // 每页显示多少条数据,如果不传,那就是显示10条
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        const offset = (pageNo - 1) * pageSize

        // id倒序
        const condition = {
            // // 排除关联表的字段
            attributes: {
                exclude: ['categoryId']
            },
            include: [
                {
                    model: Category,
                    as: 'category',
                    // 只返回id和name字段
                    attributes: ['name']
                }
            ],
            where: {
                userId: userId,
            },
            limit: pageSize,
            offset: offset
        }
        const { count, rows } = await Courses.findAndCountAll(condition);

        const updatedRows = handleobj(rows)

        // 返回或使用处理后的结果
        success(res, '查询课程成功!', {
            courses: updatedRows,
            paginations: {
                total: count,
                pageNo,
                pageSize
            }
        });
    } catch (error) {
        fail(res, error)
    }
}
//通过分类查询课程列表
exports.getcoursesbycategory = async (req, res) => {
    try {
        const { id } = req.params;
        const query = req.query

        const courses = await Courses.findOne({ where: { categoryId: id } });
        if (!courses) {
            throw new NotFounError(`ID:${id}的分类没有找到课程`);
        }
        // 当前是第几页,如果不传默认第一页
        const pageNo = Math.abs(Number(query.pageNo)) || 1
        // 每页显示多少条数据,如果不传,那就是显示10条
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        const offset = (pageNo - 1) * pageSize

        // id倒序
        const condition = {
            where: {
                categoryId: id,
            },
            // order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        }
        const { count, rows } = await Courses.findAndCountAll(condition);

        success(res, '查询课程成功!', {
            courses: rows,
            paginations: {
                total: count,
                pageNo,
                pageSize
            }
        })
    } catch (error) {
        fail(res, error)
    }
}
// 查询详情处理函数
exports.getcoursesdetail = async (req, res) => {
    console.log(req.params);
    try {
        const courses = await getCourses(req)
        success(res, '查询课程成功!', { courses })
    } catch (error) {
        fail(res, error)
    }
}
// 新增课程处理函数
exports.addcourses = async (req, res,) => {
    try {
        // 白名单过滤
        const body = filterBody(req)
        const courses = await Courses.create(body)
        success(res, "创建课程成功!", { courses }, 201)
    } catch (error) {
        fail(res, error)
    }

}
// 删除课程处理函数
exports.deletecourses = async (req, res) => {
    try {
        const courses = await getCourses(req)
        await courses.destroy()
        success(res, "删除课程成功!")
    } catch (error) {
        fail(res, error)
    }
}
// 更新课程处理函数
exports.updatecourses = async (req, res) => {
    try {
        const courses = await getCourses(req)
        // 白名单过滤
        const body = filterBody(req)
        await courses.update(body)
        res.json({
            status: true,
            message: "更新课程成功!",
            data: courses
        })
    } catch (error) {
        fail(res, error)
    }

}

/**
 * 公共方法：查询当前课程
 */
async function getCourses(req) {
    //获取课程 ID
    const { id } = req.params;
    //通过 ID 查询课程当前课程
    const courses = await Courses.findByPk(id)
    //如果没有找到,就抛出异常
    if (!courses) {
        throw new NotFounError(`ID:${id}的课程没有找到`)
    }
    return courses
}

/**
 * 公共方法:白名单id过滤
 * @param req
 * @returns 
 */
function filterBody(req) {
    return {
        categoryId: req.body.categoryId,
        userId: req.body.userId,
        name: req.body.name,
        image: req.body.image,
        introduction: req.body.introduction,
        content: req.body.content,
        likeCount: req.body.likeCount,
        chaptedAt: req.body.chaptedAt,
    }
}
/**
 * 公共方法:处理关联返回对象
 * @param req
 * @returns 
 */
function handleobj(rows,...args) {
    // 将每一行数据转换为纯 JS 对象，并添加 Categoryname 属性
    const updatedRows = rows.map((item) => {
        const plainItem = item.get({ plain: true }); // 确保获取的是纯 JS 对象而非 Sequelize 实例
        return {
            ...plainItem,
            Categoryname: plainItem.category ? plainItem.category.name : null, // 添加 Categoryname 属性
        };
    });

    // 移除可能引起循环引用的属性（如 'category'），如果你不再需要它们
    updatedRows.forEach(row => delete row.category);
    return updatedRows;
}